const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
const path = require('node:path');
const storagePath = path.join(app.getPath('userData'), 'storage.json');
let currentLang = '';
function registerLanguageIpcMain() {
    ipcMain.on('get-language', getLanguage);
    ipcMain.on('set-language', setLanguage);
    ipcMain.handle('set-language-file', loadLanguageFiles);
}

function setItem(event, key, value) {
    const data = fs.existsSync(storagePath) ?
        JSON.parse(fs.readFileSync(storagePath)) : {};
    data[key] = value;
    fs.writeFileSync(storagePath, JSON.stringify(data));
}

function getItem(event, key) {
    const data = fs.existsSync(storagePath) ? JSON.parse(fs.readFileSync(storagePath)) : {};
    return data[key] || '';
}

///获取当前本地语言类型
async function getLanguage(event) {
    currentLang = getItem(null, 'lang') || 'en';
    BrowserWindow.getAllWindows().forEach(win => {
        win.webContents.send('change-language', currentLang);
    });
}

///设置当前语言
function setLanguage(event, lang) {
    setItem(null, 'lang', lang);
    getLanguage();
}

///获取translations 
async function loadLanguageFiles(event, map) {
    const translations = {};
    for (const [lang, filePath] of Object.entries(map)) {
        translations[lang] = require(filePath);
    }
    return translations;
}

// ✅ CommonJS 导出
module.exports = { registerLanguageIpcMain };
